/*
 * Authors: Alex Attar & Kevin El Hage
 * ID: 9765727
 * Date: 9/3/2012
 * 
 */

package taskManagerSystem.ControllerSubsystem;

import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;

import taskManagerSystem.ModelSubsystem.Model;
import taskManagerSystem.ViewSubsystem.TableMod;
import taskManagerSystem.ViewSubsystem.View;

/* 
 * TaskTableListener is the listener used for tables (ie: Task and Person views).
 * Whenever a table is changed, it calls the tableChanged method and updates accordingly.
 */
public class TaskTableListener implements TableModelListener {
	Model model;
	View view;
	
	/*
	 * The constructor receives references to the model and view so that
	 * they can be updated as needed. 
	 */
	public TaskTableListener(Model model, View view) {
		this.model = model;
		this.view = view;
	}
	
	/*
	 * tableChanged is the method called by a table that has been altered.
	 */
    public void tableChanged(TableModelEvent evt) {
    	
    	if(evt.getType() == TableModelEvent.INSERT)
    	{
    		System.out.println("Caught");
    	}
    	
    	else if (evt.getType() == TableModelEvent.UPDATE) {
            int column = evt.getColumn();
            int row = evt.getFirstRow();
            Object src = evt.getSource();
            if (src.getClass() == TableMod.class)
            {
                TableMod tableM = (TableMod) evt.getSource();
                
                
                int taskID = Integer.parseInt((String) tableM.getValueAt(row, 0));
                Object newValue = tableM.getValueAt(row, column);
                /*
                 *  If newValue is not null, then an existing task was changed.
                 *  The model is informed of the change. 
                 */ 
                if (newValue != null)
                	model.updateTask(taskID, column, newValue);
                //
                view.populatePersonTable();
                view.populateTreeView();
                view.populateGanttView();
                
                tableM.removeTableModelListener(this);
                view.populateTaskTable();
                tableM.addTableModelListener(this);
            }
        }

    }
}
